package ink.teamwork.battery.controller;

import ink.teamwork.battery.model.CurrentUser;
import ink.teamwork.battery.service.RedisService;
import ink.teamwork.battery.util.JSONUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.io.IOException;
import java.util.Objects;

public abstract class BaseController {

    public Logger logger = LoggerFactory.getLogger(BaseController.class);

    private static final ThreadLocal<HttpServletRequest> REQUEST_CONTAINER = new ThreadLocal<>();
    private static final ThreadLocal<HttpServletResponse> RESPONSE_CONTAINER = new ThreadLocal<>();

    @Autowired
    private RedisService redisService;

    public static void remove() {
        REQUEST_CONTAINER.remove();
        RESPONSE_CONTAINER.remove();
    }

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request,
                             HttpServletResponse response) {
        REQUEST_CONTAINER.set(request);
        RESPONSE_CONTAINER.set(response);
    }


    public String getToken() {
        HttpServletRequest request = this.getRequest();
        if (Objects.isNull(request)) {
            return "";
        } else {
            String token = request.getParameter("token");
            if (!StringUtils.hasText(token)) {
                token = Objects.isNull(request.getAttribute("token")) ? "" : request.getAttribute("token").toString();
            }

            if (!StringUtils.hasText(token)) {
                token = request.getHeader("token");
            }

            return token;
        }
    }

    public CurrentUser getCurrentUser() {
        Object accessToken = REQUEST_CONTAINER.get().getAttribute("accessToken");
        if (accessToken == null) {
            return null;
        }
        return JSONUtils.jsonToBean(redisService.get(accessToken.toString()), CurrentUser.class);
    }

    protected HttpServletRequest getRequest() {
        return REQUEST_CONTAINER.get();
    }

    protected HttpServletResponse getResponse() {
        return RESPONSE_CONTAINER.get();
    }

    protected void download(String fileName) {
        getResponse().setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s", fileName));
        getResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM.getType());
        try {
            getResponse().flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
